/*
 * Copyright (c) 2007-2020 西安交通信息投资营运有限公司 版权所有
 * 作者:马星俊
 */

import React, {FC, useCallback, useMemo, useRef, useState} from 'react';
import {ProColumns} from '@ant-design/pro-table';
import service from './service';
import {SysDeptModel} from './data';
import Details from './components/Details';
import Edit from './components/Edit';
import useList, {ListOperate} from "@/hooks/useList";
import useDelete from "@/hooks/useDelete";
import ProTableCrud, {OptionColumnPosition, ProTableCrudOperate} from "@/components/ProTableCrud";
import {Button, Input, Switch} from "antd";
import {eachTree, getStatusEnum, hasPermission, listToTree} from "@/utils/utils";
import style from "./index.less";
import XtraTree from "@/lib/XtraTree";
import XtraModal, {XtraModalMethods} from "@/lib/XtraModal";
import config from "@/config";
import Permission from "@/components/Permission";
import {DialogOperate, TreeNodeModel} from "@/global";
import useDialog from "@/hooks/useDialog";


/** 组织机构模块 */
const SysDeptPage: FC = () => {
  const editOperate = useDialog();
  const detailsOperate = useDialog();

  const [expandKeys, setExpandKeys] = useState<string[]>([]);
  const dragModal = useRef<XtraModalMethods>(null);
  //List
  const listOperate = useList<SysDeptModel>({
    onLoad: (params) => {
      return service.selectList(params).then(r => {
        let esz: string[] = [];
        r.data.forEach((p: SysDeptModel) => {
          esz.push(p.id);
        });
        setExpandKeys(esz);
        const treeData: TreeNodeModel[] = listToTree(r.data);
        eachTree(treeData, obj => {
          if (obj.children) {
            obj.icon = (<i className='fa fa-folder'/>);
          } else {
            obj.icon = (<i className='fa fa-file'/>);
          }
        })
        return {success: true, total: r.data.length, data: treeData};
      });
    },
    onExport: (params) => service.export(params),
  });

  //Delete
  const deleteOperate = useDelete<SysDeptModel>({
    onDelete: (ids, _) => service.delete(ids.join()),
    onDeleteSucess: listOperate.handleReload,
  });

  //模块拖拽窗口[确定]按钮回调函数
  const onDragModalOk = useCallback(() => {
    dragModal.current?.hide();
    listOperate.handleReload();
  }, []);

  const newRecord = useCallback((newModel: {}) => {
    editOperate.show({
      created: true,
      onSubmitSucess: listOperate.handleReload,
      newModel
    });
  }, []);

  const onExpand = (expanded: boolean, record: SysDeptModel) => {
    const index = expandKeys.findIndex(p => p === record.id);
    if (!expanded && index > -1) {
      //删除
      setExpandKeys(o => {
        o.splice(index, 1);
        return o;
      });
    }
    if (expanded && index == -1) {
      //添加
      setExpandKeys(o => {
        o.push(record.id);
        return o;
      });
    }
  }

  //表格列
  const cols = useMemo(() => getCols(listOperate, detailsOperate), []);

  //增删改查选项
  const tableOperate: ProTableCrudOperate<SysDeptModel> = {
    cols,
    showCreate: hasPermission(config.permission.sysRole.insert),
    showEdit: hasPermission(config.permission.sysRole.update),
    showDelete: hasPermission(config.permission.sysRole.delete),
    showDetails: hasPermission(config.permission.sysRole.select),
    showExport: hasPermission(config.permission.sysRole.export),
    listOperate,
    editOperate,
    deleteOperate,
    detailsOperate,
    optionColumnPosition: OptionColumnPosition.Right,
    optionColumnWidth: 160,
    getColumnComandItems: (_, r) => ['details', (
      <a key="cmd-create" onClick={() => newRecord({parentId: r.id})}>新建</a>
    ), 'edit', 'delete'],
    getToolbarItems: () => ['create', 'delete', 'export', (
      <Button onClick={() => {
        //setDragVisable(v=>!v);
        dragModal.current?.show();
      }}>
        <i className="fal fa-chart-network"/>
        拖拽
      </Button>
    )],
    getEditElement: (props) => (<Edit {...props}/>),
    getDetailsElement: (props) => (<Details {...props}/>),
  };

  return (
    <>
      <Permission code={config.permission.sysDept.select}>
        <ProTableCrud
          headerTitle="系统机构列表"
          pagination={false}
          expandable={{expandedRowKeys: expandKeys, onExpand}}
          operate={tableOperate}
          deps={[expandKeys]}
        />
      </Permission>
      <XtraModal ref={dragModal} title="机构拖拽" onOk={onDragModalOk} cancelButtonVisible={false}>
        <XtraTree onLoadTreeData={service.selectTreeList} onSaveDndNodes={service.updateDnd}/>
      </XtraModal>
    </>
  );
};

//表格列
function getCols(listOperate: ListOperate<SysDeptModel>, detailsOperate: DialogOperate): (ProColumns<SysDeptModel>[]) {
  return [
    {
      title: '关键字',
      key: 'name',
      hideInTable: true,
      renderFormItem: (item, {type, defaultRender, ...rest}) => {
        return (<Input {...rest} placeholder="组织机构名称/简拼查询"/>)
      },
    },
    {
      title: '机构名称',
      dataIndex: 'name',
      width: 200,
      hideInSearch: true,
      ellipsis: true,
      sorter: false,
      align: 'left',
      render: (_, r) => {
        return (
          <div className={style.overflow}>
            <a onClick={() => detailsOperate.show({id: r.id})}>{r.icon}&nbsp;{r.name}</a>
          </div>
        );
      },
    },
    {
      title: '机构编码',
      dataIndex: 'code',
      hideInSearch: true,
      ellipsis: true,
      align: 'center',
    },
    {
      title: '负责人',
      dataIndex: 'leaderName',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '机构类型',
      dataIndex: 'category',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '机构性质',
      dataIndex: 'nature',
      hideInSearch: true,
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 50,
      filters: undefined,
      initialValue: 'null',
      valueEnum: getStatusEnum(),
      align: 'center',
      formItemProps: {
        'onSelect': listOperate.handleSearch
      },
      render: (_, r) => (
        <Switch key={r.id}
                size={"small"}
                checked={r.status}
                onClick={() => {
                  service.updateStatus(r.id, !r.status).then(() => {
                    listOperate.handleReload();
                  });
                }}
        />
      ),
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
      ellipsis: false,
      align: 'center',
    },
  ]
}

export default SysDeptPage;

